<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-12 16:30:58
 * @FilePath: \usp-osm-frondend\src\views\serviceCenter\serviceMgmt\updateService.vue
-->
<template>
  <div
    class="source"
    v-loading="pageLoading"
    :element-loading-text="loadingText"
  >
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDrawer"
        ><i class="el-icon-back"></i
      ></span>
      <h1 v-if="pageType === 'detail'" style="display: inline-block; margin-left: 10px">
        详情
      </h1>
      <h1 v-else-if="pageType === 'add'" style="display: inline-block; margin-left: 10px">
        新增服务
      </h1>
      <h1 v-else-if="pageType === 'edit'" style="display: inline-block; margin-left: 10px">
        修改服务
      </h1>
    </div>
    <div class="base-info">
      <el-form
        :model="editData"
        :rules="rules"
        label-position="left"
        ref="editForm"
        label-width="170px"
        size="small"
        class="dialogForm"
      >
        <el-row :gutter="20">
          <el-form-item
            prop="serviceCode"
            class="formPosition"
            label="服务编码"
          >
            <el-input
              type="text"
              v-model="editData.code"
              placeholder="服务编码"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="name"
            class="formPosition"
            label="服务名称"
          >
            <el-input
              type="text"
              :disabled="pageType === 'detail'"
              v-model="editData.name"
              @input="editData.name=editData.name.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
              placeholder="服务名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="serviceProviderName"
            class="formPosition"
            label="服务商"
          >
            <el-autocomplete
              v-model="editData.serviceProviderName"
              value-key="name"
              :disabled="editData.isBoundCoupon === '1' || pageType === 'detail'"
              size="mini"
              :debounce="500"
              :fetch-suggestions="querySearchAsync"
              placeholder="请根据供应商CODE/进行选择"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item prop="type" class="formPosition" label="服务类型">
            <el-select v-model="editData.type"
              placeholder="服务类型"
              :disabled="pageType === 'detail'"
              popper-class="select-class"
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in lookupItems.SERVICETYPE"
                :key="item.dicCode"
                :label="item.dicName"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isBoundCoupon" class="formPosition" label="是否绑定券池">
            <el-radio-group :disabled="status === '3' || pageType === 'detail'" @change="isBindChange" v-model="editData.isBoundCoupon">
              <el-radio
                v-for="(item, index) in isBindList"
                :key="index"
                :label="item.dicCode"
              >
                {{ item.dicName }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div v-if="editData.isBoundCoupon === '1'" class="service-info">
      <h2 class="model-title">券池</h2>
      <el-row :gutter="20">
        <div class="mb-lg">
          <v-table
            :data="tableData"
            class="service-table"
            ref="multipleTable"
            :listLoading="listLoading"
            :loadingText="loadingText"
            border
            :pagination="false"
            v-on:handleSelectionChange="handleSelectionChange"
          >
            <div slot="header">
              <el-button
                @click="addCoupon"
                icon="el-icon-plus"
                class="dark-btn"
                style="margin-bottom: 0 !important"
              >
                添加券池
              </el-button>
              <el-button
                @click="cancelCoupon"
                icon="el-icon-delete"
                :disabled="isCancel"
                class="dark-btn"
                style="margin-bottom: 0 !important"
              >
                取消券池
              </el-button>
            </div>
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              label="券池编号"
              align="center"
              min-width="120"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>
                  {{ scope.row.couponCode }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="券名称"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <!-- {{ getDictionaryNameByCode('LABELTYPE', scope.row.packgeType) }} -->
                {{ scope.row.couponName }}
              </template>
            </el-table-column>
            <el-table-column
              label="业务类型"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ getDictionaryNameByCode('BUSINESSTYPE', scope.row.businessType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="面值"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.faceValue }}
              </template>
            </el-table-column>
            <el-table-column
              label="服务商"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.serviceProvidersName }}
              </template>
            </el-table-column>
          </v-table>
        </div>
      </el-row>
    </div>
    <div class="footer">
      <div v-if="pageType !== 'detail'" class="footer-btn">
        <el-button @click="closeDrawer" class="white-btn">取消</el-button>
        <el-button @click="saveEdit('editForm')" class="dark-btn">
          保存
        </el-button>
      </div>
    </div>

    <add-coupon ref="addDialog"></add-coupon>
  </div>
</template>

<script>
import { xor, cloneDeep } from 'lodash'
import { saveServiceEdit, getServiceDetail, getServiceProviderList } from '@/api/service'
import addCoupon from './dialog/addCoupon'
import { mapGetters } from 'vuex'
import VTable from '@/components/PageTable/index'
import { common } from '@/mixins/common'
import { setRouterParams, getRouterParams } from '@/utils/auth'

export default {
  name: 'updateService',
  mixins: [common],
  components: {
    VTable,
    addCoupon
  },
  data () {
    return {
      tableData: [],
      editData: {
        code: '',
        isBoundCoupon: '',
        name: '',
        serviceProviderName: '',
        serviceProviderCode: '',
        responseServicePackageDetailVoList: [],
        type: ''
      },
      serviceProviderCode: '',
      pageLoading: false,
      listLoading: false,
      isUpdateNum: 0,
      isCancel: true,
      isAdd: true,
      addSave: false,
      loadingText: '加载中...',
      showNameRequire: false,
      queryDatas: [],
      inputData: [],
      selectList: [],
      selectData: {},
      status: '',
      pageType: '',
      isBindList: [
        {
          dicCode: '0',
          dicName: '否'
        },
        {
          dicCode: '1',
          dicName: '是'
        }
      ],
      rules: {
        name: [
          {
            required: true,
            message: '服务名称不能为空'
          }
        ],
        isBoundCoupon: [
          {
            required: true,
            message: '请选择其中一项',
            trigger: 'blur'
          }
        ],
        serviceProviderName: [
          {
            required: true,
            message: '请选择服务商',
            trigger: ['change', 'blur']
          }
        ],
        type: [
          {
            required: true,
            message: '请选择服务类型',
            trigger: 'change'
          }
        ]
      },
      isSave: false,
      deleteObjList: [],
      deleteObj: {
        id: '',
        isDeleted: '1'
      }
    }
  },
  created () {
    this.attributeAction(this.$route.params.id)
  },
  mounted () {
    this.loadAll()
    this.getDataChange()
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  watch: {
    queryDatas: {
      handler (val) {
        if (val.length === 0) {
          this.addSave = true
        } else {
          this.addSave = false
        }
      },
      deep: true
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.isSave) {
      next()
    } else {
      if (this.isUpdateNum > 1) {
        this.$confirm(this.$t('closeDrawerTip'), '', {
          confirmButtonText: this.$t('confirmYes'),
          cancelButtonText: this.$t('confirmNo')
        })
          .then(() => {
            next()
          })
          .catch(() => {
            next(false)
            this.$setMenuActived(this.$route.path)
          })
      } else {
        next()
      }
    }
  },
  methods: {
    // 根据orgId获取语言数据
    getDataChange () {
      this.isUpdateNum = 0
      /* === 弹窗监听 start ==== */
      this.$watch(
        'editData',
        function () {
          this.isUpdateNum++
        },
        { deep: true }
      )
      /* === 弹窗监听 end ==== */
    },
    handleSelectionChange (val) {
      this.selectList = val
      if (this.selectList.length !== 0) {
        this.isCancel = false
      } else {
        this.isCancel = true
      }
    },
    isBindChange (val) {
      if (val !== null) {
        this.editData.name = ''
        this.editData.serviceProviderName = ''
        this.editData.serviceProviderCode = ''
        this.editData.responseServicePackageDetailVoList = []
      }
    },
    getTableData (data) {
      let serviceProviderArr = []
      let serviceProviderCodeArr = []
      data.forEach(item => {
        item.couponId = item.id
        item.serviceRightId = this.id
        delete item.id
        item.couponValue = item.faceValue
        item.couponSource = item.source
        this.tableData.push(item)
      })
      this.tableData.forEach(item => {
        serviceProviderArr.push(item.serviceProvidersName)
        serviceProviderCodeArr.push(item.serviceProvidersCode)
      })
      serviceProviderArr = [...new Set(serviceProviderArr)]
      serviceProviderCodeArr = [...new Set(serviceProviderCodeArr)]
      this.editData.serviceProviderName = serviceProviderArr.join(', ')
      this.editData.serviceProviderCode = serviceProviderCodeArr.join(', ')
    },
    saveEdit (formName) {
      // 保存新增修改
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editData.isBoundCoupon === '1') {
            if (this.tableData.length === 0) {
              this.$alert('请添加券池')
            } else {
              this.saveValid(this.editData.serviceProviderName, this.editData.serviceProviderCode)
            }
          } else {
            this.saveValid()
          }
        } else {
          return false
        }
      })
    },
    saveValid (providerName, providerCode) {
      const self = this
      if (this.addSave) {
        this.$alert('服务商不存在，请重新选择')
      } else {
        this.pageLoading = true
        self.editData.name = self.editData.name.trim()
        const requestServiceDetailVoList = []

        if (!this.isAdd) {
          requestServiceDetailVoList.push(...self.deleteObjList)
        }
        requestServiceDetailVoList.push(...self.tableData)
        const data = {
          id: self.id,
          code: self.editData.code,
          name: self.editData.name,
          type: self.editData.type,
          isBoundCoupon: self.editData.isBoundCoupon,
          serviceProviderCode: self.editData.isBoundCoupon === '0' ? self.selectData.code : providerCode,
          serviceProviderName: self.editData.isBoundCoupon === '0' ? self.selectData.name : providerName,
          serviceProviderId: self.serviceProviderId,
          requestServiceDetailVoList: requestServiceDetailVoList
        }
        saveServiceEdit(data)
          .then((response) => {
            // 调用接口保存新增修改attribute
            const data = response
            this.pageLoading = false
            if (Number(data.code) === 1) {
              self.$emit('search')
              self.$alert('数据保存成功', {
                confirmButtonText: '确定',
                callback: (action) => {
                  this.$router.push({ name: 'serviceMgmt' })
                }
              })
              this.isSave = true
            } else {
              this.$confirm(this.$t(response.code), {
                confirmButtonText: '确认',
                showCancelButton: false
              })
            }
          })
          .catch((error) => {
            this.$confirm(error, {
              confirmbuttontext: this.$t('confirmOK'),
              showcancelbutton: false
            })
          })
      }
    },
    closeDrawer () {
      this.$router.push({ name: 'serviceMgmt' })
    },
    attributeAction (id) {
      const name = this.$route.name
      this.pageType = this.$route.params.type
      if (this.pageType === 'detail') {
        this.$route.meta.title = '详情'
        this.$route.meta.titlePath = '详情'
      } else if (this.pageType === 'edit') {
        this.$route.meta.title = '修改服务'
        this.$route.meta.titlePath = '修改服务'
      } else if (this.pageType === 'add') {
        this.$route.meta.title = '新增服务'
        this.$route.meta.titlePath = '新增服务'
      }
      if (id) {
        this.id = id
        this.isAdd = false
        setRouterParams(this.$route)
        this.edit(this.id)
      } else {
        if (name === 'editService') {
          this.isAdd = false
          const routeParams = getRouterParams(this.$route)
          this.pageType = routeParams.type
          this.id = routeParams.id
          this.edit(this.id)
        } else {
          this.isAdd = true
          this.pageType = 'add'
          this.initpage()
        }
      }
    },
    edit (id) {
      const self = this
      const model = { id: id }
      self.pageLoading = true
      getServiceDetail(model)
        .then((response) => {
          // 编辑Attribute
          const data = response
          if (data) {
            self.pageLoading = false
            if (Number(data.code) === 1) {
              const obj = data.obj
              self.filterData(obj)
              // self.tableData = obj.responseServiceDetailVoList
            } else if (Number(data.code) === 0) {
              self.$confirm(data.msg, {
                confirmButtonText: '确认',
                showCancelButton: false
              })
            } else {
              self.$alert(this.$t(response.code))
            }
          }
        })
        .catch((_) => {
          this.pageLoading = false
        })
    },
    initpage () {
      // 初始页面值
      this.editData = {
        code: '',
        isBoundCoupon: '0',
        name: '',
        serviceProviderName: '',
        serviceProviderCode: '',
        responseServicePackageDetailVoList: [],
        type: ''
      }
    },
    filterData (allData) {
      if (allData) {
        this.status = allData.status
        this.editData = {
          code: allData.code,
          isBoundCoupon: allData.isBoundCoupon,
          name: allData.name,
          type: allData.type,
          serviceProviderName: allData.serviceProviderName,
          serviceProviderCode: allData.serviceProviderCode,
          serviceProviderId: allData.serviceProviderId,
          responseServiceDetailVoList: allData.responseServiceDetailVoList || []
        }
        if (allData.responseServiceDetailVoList) {
          const tableArr = allData.responseServiceDetailVoList
          this.tableData = allData.responseServiceDetailVoList || []
          tableArr.forEach(item => {
            this.tableData.forEach(ele => {
              ele.faceValue = item.couponValue
              ele.source = item.couponSource
            })
          })
        }
      }
    },
    addCoupon () {
      const idList = []
      if (this.tableData && this.tableData.length > 0) {
        this.tableData.forEach(item => {
          idList.push(item.couponId)
        })
      }
      this.$refs.addDialog.open(idList)
    },
    cancelCoupon () {
      this.$confirm('确定取消吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.tableData = xor(this.tableData, this.selectList)
        let nameArr = []
        let codeArr = []
        this.tableData.forEach(item => {
          nameArr.push(item.serviceProvidersName)
          codeArr.push(item.serviceProvidersCode)
        })
        nameArr = [...new Set(nameArr)]
        codeArr = [...new Set(codeArr)]
        this.editData.serviceProviderName = nameArr.join(', ')
        this.editData.serviceProviderCode = codeArr.join(', ')

        this.deleteObjList = cloneDeep(this.tableData)
        this.selectList.forEach(item => {
          this.deleteObjList.push(this.deleteObj = {
            id: item.id,
            isDeleted: '1'
          })
        })
        this.$alert('取消成功')
      })
    },
    loadAll () {
      const params = {
        code: '',
        contactAddress: '',
        contactEmail: '',
        contactPhone: '',
        contactUser: '',
        name: '',
        status: '1',
        type: ''
      }
      getServiceProviderList(params).then((response) => {
        const data = response
        if (Number(data.code) === 1) {
          this.inputData = data.obj
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    querySearchAsync (queryString, cb) {
      const results = queryString
        ? this.inputData.filter(this.createStateFilter(queryString))
        : this.inputData
      this.queryDatas = results
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 3000 * Math.random())
    },
    createStateFilter (queryString) {
      return (state) => {
        return (
          state.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0 || state.code.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    handleSelect (item) {
      this.selectData = item
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.langBox {
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  padding: 2px 0px;
  width: 50px;
  float: left;
  margin-left: 10px;
  span {
    display: block;
    line-height: 12px;
  }
  .lang {
    border-bottom: 1px dashed #ccc;
  }
}
.dialogForm {
  .formPosition {
    position: relative;
  }
  .descSty {
    position: absolute;
    top: -152px;
    left: 115px;
  }
}

/deep/ .el-form--label-left .el-form-item__label {
  text-align: right;
  padding-right: 20px;
}

.service-table /deep/ .el-pagination {
  display: none;
}

.model-title {
  background: #e9ecf1;
  border-left: 4px solid #00b9ad;
  line-height: 40px;
  font-size: 14px;
  padding-left: 10px;
  margin-bottom: 10px;
}

/deep/ .el-autocomplete {
  width: 100% ;
}

/deep/ .el-select-dropdown__list {
  height: 140px;
}

</style>
